using System;

namespace Tycho.Parser.Peg {
    public class ChoiceRule : Rule {
        private readonly IRule[] Rules;

        public ChoiceRule (params IRule[] rules) {
            Rules = rules;
        }

        public override Yield Parse (char[] source, int index, ParseContext context, string sourceString, ParseEnvironment environment, Func<RuleParseResult, Yield> continuation) {
            return Trampoline.Enumerate<IRule> (Rules, (rule, next) => {
                return rule.Parse (source, index, context, sourceString, environment, result => {
                    if (result != null) {
                        return () => continuation (result);
                    } else {
                        return next;
                    }
                });
            }, () => continuation (null));
        }
    }
}